
from datetime import datetime
import os
import time
import json
from PySide6.QtWidgets import (QApplication, QMainWindow, QTabWidget, QWidget, QVBoxLayout, 
                             QHBoxLayout, QLabel, QPushButton, QTextEdit, QTreeWidget, 
                             QTreeWidgetItem, QComboBox, QMessageBox, QSplitter, QFrame, 
                             QListWidget, QListWidgetItem, QToolBar, QInputDialog, 
                             QMenu, QDialog, QFormLayout, QGroupBox, QProgressBar, 
                             QTableWidget, QTableWidgetItem, QHeaderView, QFileDialog, QLineEdit,
                             QSpinBox, QCheckBox, QDialogButtonBox, QTextBrowser)
from PySide6.QtCore import Qt, QThread, Signal, Slot, QDateTime, QTimer, QObject,QSettings,QThreadPool,QEvent
from PySide6.QtGui import QFont, QColor, QIcon, QAction

from gui.utils.annotation_manager import CommandType, DataManager, ResponseStatus


# 模型管理对话框
class ModelManagerDialog(QDialog):
    def __init__(self, data_manager, parent=None):
        super().__init__(parent)
        self.data_manager:DataManager = data_manager
        self.setWindowTitle("模型管理")
        self.resize(500, 400)
        
        layout = QVBoxLayout(self)
        
        # 模型列表
        self.model_table = QTableWidget()
        self.model_table.setColumnCount(4)
        self.model_table.setHorizontalHeaderLabels(["模型名称", "标签", "检测类型", "操作"])
        self.model_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.model_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.model_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
        self.model_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents)
        layout.addWidget(self.model_table)
        
        # 添加模型按钮
        add_button = QPushButton("添加模型")
        add_button.clicked.connect(self.add_model)
        layout.addWidget(add_button)
        
        # 刷新模型列表 
        self.data_manager.signals.command_result.connect(self.on_command_result)
        self.data_manager.enqueue_command(CommandType.GET_ALL_MODELS)
    
    @Slot(str, dict, str)
    def on_command_result(self, cmd_type, result, status):
        """命令执行结果回调"""
        if status == ResponseStatus.SUCCESS:
            if cmd_type == CommandType.GET_ALL_MODELS:
                self.refresh_models(result.get("models", {}))
            else:
                self.data_manager.enqueue_command(CommandType.GET_ALL_MODELS)
        elif status == ResponseStatus.FAILURE:
            print(f"命令执行失败: {cmd_type}, 错误: {result.get('error', '未知错误')}")
            
    def refresh_models(self,models):
        self.model_table.setRowCount(0)
        for row, (model_name, data) in enumerate(models.items()):
            self.model_table.insertRow(row)
            
            # 模型名称
            self.model_table.setItem(row, 0, QTableWidgetItem(model_name))
            
            # 标签
            labels_str = ", ".join(data["labels"])
            self.model_table.setItem(row, 1, QTableWidgetItem(labels_str))
            
            # 检测类型
            self.model_table.setItem(row, 2, QTableWidgetItem(data["det_type"]))
            
            # 操作按钮
            delete_button = QPushButton("删除")
            delete_button.clicked.connect(lambda checked, m=model_name: self.delete_model(m))
            self.model_table.setCellWidget(row, 3, delete_button)
    
    def add_model(self):
        dialog = AddModelDialog(self)
        if dialog.exec():
            model_name, labels, det_type = dialog.get_model_data()
            params = {
                "model_name": model_name,
                "labels": labels,
                "det_type": det_type
            }
            self.data_manager.enqueue_command(CommandType.ADD_MODEL,params)
    
    def delete_model(self, model_name):
        reply = QMessageBox.question(
            self, "确认", f"确定要删除模型 '{model_name}' 吗？",
            QMessageBox.Yes | QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            params = {
                "model_name": model_name,
            }
            self.data_manager.enqueue_command(CommandType.ADD_MODEL,params)

# 添加模型对话框
class AddModelDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("添加模型")
        self.resize(300, 200)
        
        layout = QVBoxLayout(self)
        
        # 表单布局
        form_layout = QFormLayout()
        
        self.model_name_edit = QLineEdit()
        self.labels_edit = QLineEdit()
        self.labels_edit.setPlaceholderText("多个标签用逗号分隔")
        self.det_type_combo = QComboBox()
        self.det_type_combo.addItems(DETECTION_TYPES)
        
        form_layout.addRow("模型名称:", self.model_name_edit)
        form_layout.addRow("标签:", self.labels_edit)
        form_layout.addRow("检测类型:", self.det_type_combo)
        
        layout.addLayout(form_layout)
        
        # 按钮
        button_layout = QHBoxLayout()
        self.ok_button = QPushButton("确定")
        self.cancel_button = QPushButton("取消")
        
        self.ok_button.clicked.connect(self.accept)
        self.cancel_button.clicked.connect(self.reject)
        
        button_layout.addWidget(self.ok_button)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
    
    def get_model_data(self):
        model_name = self.model_name_edit.text()
        labels = self.labels_edit.text().split(",") if self.labels_edit.text() else []
        det_type = self.det_type_combo.currentText()
        return model_name, labels, det_type
